package net.quanter.shield.mq.rocketmq.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

public class ObjectUtils {

    public static Object byteArrayToObject(Type type, byte[] b) {
        byte[] decode = Base64.decode(b);
        if (String.class.getTypeName().equals(type.getTypeName())) {
            return new String(decode, StandardCharsets.UTF_8);
        } else if (Integer.class.getTypeName().equals(type.getTypeName())) {
            String str = new String(decode, StandardCharsets.UTF_8);
            return Integer.parseInt(str);
        } else if (Long.class.getTypeName().equals(type.getTypeName())) {
            String str = new String(decode, StandardCharsets.UTF_8);
            return Long.parseLong(str);
        } else if (Short.class.getTypeName().equals(type.getTypeName())) {
            String str = new String(decode, StandardCharsets.UTF_8);
            return Short.parseShort(str);
        } else if (Double.class.getTypeName().equals(type.getTypeName())) {
            String str = new String(decode, StandardCharsets.UTF_8);
            return Double.parseDouble(str);
        } else if (Float.class.getTypeName().equals(type.getTypeName())) {
            String str = new String(decode, StandardCharsets.UTF_8);
            return Float.parseFloat(str);
        } else {
            return Convert.convert(type, decode);
        }
    }

    public static byte[] objectToByteArray(Object obj) {
        if (obj == null) {
            return new byte[0];
        }
        Class c = obj.getClass();
        if (String.class.equals(c)) {
            String str = (String) obj;
            byte[] b = stringToByteArray(str);
            return Base64.encode(b, false);
        } else if (Integer.class.equals(c)
                || Long.class.equals(c)
                || Short.class.equals(c)
                || Double.class.equals(c)
                || Float.class.equals(c)
        ) {
            String str = obj.toString();
            byte[] b = stringToByteArray(str);
            return Base64.encode(b, false);
        } else {
            return Base64.encode(Convert.toPrimitiveByteArray(obj), false);
        }
    }

    public static byte[] stringToByteArray(String obj) {
        return obj.getBytes(StandardCharsets.UTF_8);
    }
}
